package com.cysoft.dao;

import com.cysoft.domain.FilterType;
import com.cysoft.domain.Machine;
import com.cysoft.domain.WheelTechType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author andaolong
 * @time 2021年3月27日11:23:11
 * 从数据库中获取数据
 */
@Component
public class MachineDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    Long taskPlanningId = 1L;

    //查询所有的device的id，返回device类型的list，里面还未填入machiningType
    public List<Machine> getDeviceListFromDB() {

        //首先查询到所有的device_id
        String sql = "select * from machine where type=1";
        //将查询到的所有device_id存到一串<Machine>的list里面
        //return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Machine.class));

        //调试用
        //List<Machine> deviceList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Machine.class));
        //for(Machine device:deviceList){
        //    System.out.println("deviceDao获取到的deviceId为："+device.getDeviceId());
        //}
        //return deviceList;

        //给从数据库中获得的device添加上id，排程的时候需要依靠这个id进行移动操作
        List<Machine> deviceList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Machine>(Machine.class){
            @Override
            public Machine mapRow(ResultSet resultSet, int i) throws SQLException {
                Machine machine = new Machine(resultSet.getInt("id"),"铸造机",resultSet.getString("name")
                ,resultSet.getInt("min_size"),resultSet.getInt("max_size"));

                //将获得的String类型的machining_type转换为MachiningType类型的machiningType
                String filterTypeListStr = resultSet.getNString("filter_type_list");
                String wheelTechTypeListStr = resultSet.getNString("wheel_tech_type_list");
                String []filterTypeArray = filterTypeListStr.split(",");
                try {
                    List<FilterType> filterTypeList = new ArrayList<>();
                    for (String filterType : filterTypeArray) {
                        filterTypeList.add(FilterType.fromStr(filterType));
                    }
                    machine.setFilterTypeList(filterTypeList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String []techTypeArray = wheelTechTypeListStr.split(",");

                List<WheelTechType> techTypeList = new ArrayList<>();
                for (String techType:techTypeArray) {
                    techTypeList.add(WheelTechType.fromStr(techType));
                }
                machine.setWheelTechTypeList(techTypeList);
                return machine;
            }
        });

        return deviceList;
    }
}
